#!/usr/bin/python
# -*- coding: utf-8 -*-

from PIL import Image
import commands


def log_deco(func):
    """
    log the func result before return
    :param func:
    :return:
    """

    def _log_deco(*args, **kwargs):
        ret = func(*args, **kwargs)
        print(ret[1])
        return ret

    return _log_deco


def make_regalur_image(img, size=(256, 256)):
    return img.resize(size).convert('RGB')


def split_image(img, part_size = (64, 64)):
    w, h = img.size
    pw, ph = part_size
    
    assert w % pw == h % ph == 0
    
    return [img.crop((i, j, i+pw, j+ph)).copy() \
                for i in xrange(0, w, pw) \
                for j in xrange(0, h, ph)]


def hist_similar(lh, rh):
    assert len(lh) == len(rh)
    return sum(1 - (0 if l == r else float(abs(l - r))/max(l, r)) for l, r in zip(lh, rh))/len(lh)


def calc_similar(li, ri):
    #return hist_similar(li.histogram(), ri.histogram())
    return sum(hist_similar(l.histogram(), r.histogram()) for l, r in zip(split_image(li), split_image(ri))) / 16.0
            

def calc_similar_by_path(lf, rf):
    li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
    return calc_similar(li, ri)


def make_doc_data(lf, rf):
    li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
    li.save(lf + '_regalur.png')
    ri.save(rf + '_regalur.png')
    fd = open('stat.csv', 'w')
    fd.write('\n'.join(l + ',' + r for l, r in zip(map(str, li.histogram()), map(str, ri.histogram()))))
#    print >>fd, '\n'
#    fd.write(','.join(map(str, ri.histogram())))
    fd.close()
    import ImageDraw
    li = li.convert('RGB')
    draw = ImageDraw.Draw(li)
    for i in xrange(0, 256, 64):
        draw.line((0, i, 256, i), fill='#ff0000')
        draw.line((i, 0, i, 256), fill='#ff0000')
    li.save(lf + '_lines.png')

@log_deco
def take_photo(image_path):
    return commands.getstatusoutput('/opt/vc/bin/raspistill -w 1500 -h 1000 -e png -o {0}'.format(image_path))

@log_deco
def del_file(image_path):
    return commands.getstatusoutput('rm {0}'.format(image_path))
    
@log_deco
def rename_file(image_path, new_image_path):
    return commands.getstatusoutput('mv {0} {1}'.format(image_path, new_image_path))


def upload_image(image_path):
    pass

if __name__ == '__main__':
    path1 = '/home/zdglf/Desktop/pic1.png'
    path2 = '/home/zdglf/Desktop/pic2.png'
    del_file(path1)
    rename_file(path2, path1)
    take_photo(path2)
    similar = calc_similar_by_path(path1, path2)
    if similar < 0.5:
        upload_image(path2)

